<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link rel="stylesheet" href="../css/mui.min.css" />
		<link rel="stylesheet" type="text/css" href="../css/iconfont.css" />
		<link rel="stylesheet" href="../css/icons-extra.css" />
		<link rel="stylesheet" href="../css/loading.css" />
		<link rel="stylesheet" href="../css/im-chat.css" />
		<style type="text/css">
			html, body {
				height: 100%;
				margin: 0px;
				padding: 0px;
				-webkit-touch-callout: none;
				-webkit-user-select: none;
				-webkit-overflow-scrolling: touch;
			}
			
			#chat-content {
				overflow-y: scroll;
				height: 100%;
			}
		</style>
	</head>

	<body>
		<div id="Loading">
			<div class="loader-inner ball-beat">
				<div></div>
				<div></div>
				<div></div>
			</div>
		</div>
		<!--下拉刷新容器-->
		<header class="mui-bar mui-bar-nav" id="mui-bar">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title" id="mui-title"></h1>
			<!--<a class="mui-icon iconfont icon-guanli1 mui-pull-right" id='btninfo'></a>-->
		</header>
		<div id="chat-content">
			<div style="padding: 50px 10px 60px;" id="chatContent"></div>
		</div>
		<nav class="mui-bar mui-bar-tab mui-bar-footer" style="background: #fff;">
			<div class="mui-input-row" style="height: 61px;">
				<label style="width: 10%;" id="vm-like" style="margin-top: -4px; padding: 6px 15px;">
                        <i id='msg-image' class="mui-icon mui-icon-camera" style="font-size: 28px; padding-top: 6px;"></i>
					 </label>
				<label id="btn-send" style="width: 18%; float:right; margin-right: 10px; margin-top: 5px;">
							<span id="btnsend" style="line-height: 30px;" >发送</span>
					</label>
				<div class="mui-input-row mui-password" style="width: 65%; margin-top: 10px;display: inline-block;margin-left: 14px;">
					<input id='txt-msg' type="text" class='mui-input' value="" />
				</div>
			</div>
		</nav>
		<div id="tempdom" style="display: none;"></div>

		<!--聊天模板-->
		<script id="chatmsgtpl" type="text/html">
			<ul class="mui-table-view">
				{{each data as item index }}
				<!--本人-->
				{{if item.data.sender == logininf.id}}
				<li class="mui-table-view-cell sendSelf">
					<div class="mui-col-xs-10">
						<h5>{{logininf.name}}</h5> {{if item.data.type == 'text'}}
						<p>
							{{item.data.content}}
						</p>
						<span data-id="{{item.data.msgid}}" style="width: 25px;height: 25px;display: inline-block;background: url(../images/err.png) no-repeat;background-size: 20px 20px;float: right;margin-top:  10px;margin-right: 5px; display: none"></span> {{else}}
						<p>
							<img src="{{ item.data.content | getThumb }}" data-preview-src="{{item.data.content}}" data-preview-group="1" style="max-width: 120px;max-height: 120px; vertical-align: middle; text-align: center; padding: 10px; display: block;" />
						</p>
						<span data-id="{{item.data.msgid}}" style="width: 25px;height: 25px;display: inline-block;background: url(../images/err.png) no-repeat;background-size: 20px 20px;float: right;margin-top:  10px;margin-right: 5px; display: none;"></span> {{/if}}
					</div>
					<div class="mui-col-xs-3">
						<!--<img class="mui-media-object mui-pull-right" src="{{logininf.avatarUrl}}">-->
						<img class="mui-media-object mui-pull-right" src="../images/qq.png">
					</div>
				</li>
				{{else}}
				<li class="mui-table-view-cell">
					<div class="mui-col-xs-3">
						<!--<img class="mui-media-object mui-pull-left" src="{{sender.avatarUrl}}">-->
						<img class="mui-media-object mui-pull-left" src="../images/qq.png">
					</div>
					<div class="mui-col-xs-10">
						<h5>{{sender.name}}</h5> {{if item.data.type == 'text'}}
						<p>{{item.data.content}}</p>
						{{else}}
						<p>
							<img src="{{ item.data.content | getThumb }}" data-preview-src="{{item.data.content}}" data-preview-group="1" style="max-width: 120px;max-height: 120px; vertical-align: middle; text-align: center; padding: 10px; display: block;" />
						</p>
						{{/if}}
					</div>
				</li>
			</ul>
			{{/if}}{{/each}}
		</script>
		<!--单聊历史记录模板-->
		<script id="chatmsghistorytpl" type="text/html">
			<ul class="mui-table-view">
				{{if totalnums > 10}}
				<div style="text-align: center; height: 60px; line-height: 60px; " class="showmore">
					<a class="chat-user" style="text-align: center; width: 100%; font-size: 14px; color: #fff; background: rgba(0, 0, 0, 0.2); padding: 4px 10px; border-radius: 15px;">
						查看更多历史
					</a>
				</div>
				{{/if}} {{each data as item index }}
				<!--本人-->
				{{if item.sender == logininf.id}}
				<li class="mui-table-view-cell sendSelf">
					<div class="mui-col-xs-10">
						<h5>{{logininf.name}}</h5> {{if item.type == 'text'}}
						<p>{{item.content}}</p>
						{{else}}
						<p>
							<img src="{{ item.content | getThumb }}" data-preview-src="{{item.content}}" data-preview-group="1" style="max-width: 120px;max-height: 120px; vertical-align: middle; text-align: center; padding: 10px; display: block;" />
						</p>
						{{/if}}
					</div>
					<div class="mui-col-xs-3">
						<!--<img class="mui-media-object mui-pull-right" src="{{logininf.avatarUrl}}">-->
						<img class="mui-media-object mui-pull-right" src="../images/qq.png">
					</div>
				</li>
				{{else}}
				<li class="mui-table-view-cell">
					<div class="mui-col-xs-3">
						<!--<img class="mui-media-object mui-pull-left" src="{{sender.avatar}}">-->
						<img class="mui-media-object mui-pull-left" src="../images/qq.png">
					</div>
					<div class="mui-col-xs-10">
						<h5>{{sender.name}}</h5> {{if item.type == 'text'}}
						<p>{{item.content}}</p>
						{{else}}
						<p>
							<img src="{{ item.content | getThumb }}" data-preview-src="{{item.content}}" data-preview-group="1" style="max-width: 120px;max-height: 120px; vertical-align: middle; text-align: center; padding: 10px; display: block;" />
						</p>
						{{/if}}
					</div>
				</li>
				{{/if}} {{/each}}
			</ul>
		</script>
		<!--群聊历史记录模板-->
		<script id="chatmsgGroupshistorytpl" type="text/html">
			<ul class="mui-table-view">
				{{if totalnums > 10}}
				<div style="text-align: center; height: 60px; line-height: 60px; " class="showmore">
					<a class="chat-user" style="text-align: center; width: 100%; font-size: 14px; color: #fff; background: rgba(0, 0, 0, 0.2); padding: 4px 10px; border-radius: 15px;">
						查看更多历史
					</a>
				</div>
				{{/if}} {{each data as item index }}
				<!--本人-->
				{{if item.sender == logininf.id}}
				<li class="mui-table-view-cell sendSelf">
					<div class="mui-col-xs-10">
						<!--<h5>{{item.senderinfo.name}}</h5>-->
						<h5>{{logininf.name}}</h5> {{if item.type == 'text'}}
						<p>{{item.content}}</p>
						{{else}}
						<p>
							<img src='{{ item.content | getThumb }}' data-preview-src="{{item.content}}" data-preview-group="1" style="max-width: 120px;max-height: 120px; vertical-align: middle; text-align: center; padding: 10px; display: block;" />
						</p>
						{{/if}}
					</div>
					<div class="mui-col-xs-3">
						<img class="mui-media-object mui-pull-right" src="../images/qq.png">
					</div>
				</li>
				{{else}}
				<li class="mui-table-view-cell">
					<div class="mui-col-xs-3">
						<img class="mui-media-object mui-pull-left" src="../images/qq.png">
					</div>
					<div class="mui-col-xs-10">
						{{if item.senderinfo != undefined}}
						<h5>{{item.senderinfo.name}}</h5> {{else}}
						<h5>未知用户</h5> {{/if}} {{if item.type == 'text'}}
						<p>{{item.content}}</p>
						{{else}}
						<p>
							<img src="{{ item.content | getThumb }}" data-preview-src="{{item.content}}" data-preview-group="1" style="max-width: 120px;max-height: 120px; vertical-align: middle; text-align: center; padding: 10px; display: block;" />
						</p>
						{{/if}}
					</div>
				</li>
				{{/if}} {{/each}}
			</ul>
		</script>
	</body>

</html>
<script type="text/javascript" src="../js/mui.min.js"></script>
<script type="text/javascript" src="../js/mui.zoom.js"></script>
<script type="text/javascript" src="../js/mui.previewimage.js"></script>
<script type="text/javascript" src="../js/jquery-2.1.0.js"></script>
<script type="text/javascript" src="../js/config.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="../js/localStorage.js"></script>
<script type="text/javascript" src="../js/template.js"></script>
<script type="text/javascript">
	template.helper('getThumb', function(imgurl) {
		var imgUrl = thumbImage(imgurl);
		return imgUrl;
	});
	mui.init();

	var chatId; //	单聊id、群聊id
	var chatName;
	var msgtype; //聊天类型
	var loginif;
	var offset = 0; //当前页码
	var limit = 10; //条数
	var totals = 0; //总条数
	var maillistInfo = localStorageFunc.get('organize');
	var userinfo;
	//页面加载后，初始化滚动条

	mui.plusReady(function() {

		var self = plus.webview.currentWebview();
		chatId = self.userid; //单聊为thatid,群聊为群聊id
		chatName = self.notestype;
		userinfo = self.chattype == '0' ? self.userinfo : '';
		msgtype = self.chattype == '0' ? 'singleChat' : 'groupChat';
		loginif = localStorageFunc.get("applogininfo");
		console.log('loginif' + JSON.stringify(loginif));

		// 初始化界面
		$("#mui-title").text(chatName);
		var html = '';
		if(self.chattype == '0') { // 单聊人员详情
			html = '<a id="btninfo" data-status="0" class="mui-icon iconfont icon-guanli1 mui-pull-right"></a>';
			getSigleChatinfo(0);
			$('#mui-bar-bottom').show();
		} else { // 群聊设置
			html = '<a id="btninfo" data-status="1" class="mui-icon mui-icon-extra mui-icon-extra-peoples mui-pull-right" data-id=' + chatId + '></a>';
			getGroupChatinfo(0);
			//checkAuthor(chatId); //	从最近会话列表进入时，验证当前用户是否属于群成员
		}
		$("#mui-bar").append(html);
		initEvt(); // 接收新消息
	});

	//	IM消息主推指定人or群
	window.addEventListener('newMsg', function(e) {
		var chatmsg = e.detail;
		console.log('chatmsg' + JSON.stringify(chatmsg));
		var flag = false;
		switch(chatmsg.type) {
			case 'singleChat':
				if(chatmsg.data.sender == chatId) { //推送到指定人
					renderDom(chatmsg, chatmsg.data.sender);
					flag = true;
				}
				break;
			case 'groupChat':
				if(chatmsg.data.sendee == chatId) {
					renderDom(chatmsg, chatmsg.data.sender);
					flag = true;
				}
				break;
			default:
				break;
		}

		if(flag) {
			//	消息推送至消息中心首页
			var msgPage = plus.webview.getWebviewById('/html/sub-message.html');
			if(msgPage) {
				chatmsg.read = 1; //代表已读，消息中心则不显示条数
				//console.log('消息页面 收到新消息通知');
				mui.fire(msgPage, 'newChatMsg', chatmsg);
			}
		}

	});

	//  接收发送回执
	window.addEventListener('msgRsp', function(e) {
		// todo 更新消息状态
		console.log('收到发送回执 ' + JSON.stringify(e.detail));
	});

	//	接收修改群名称
	window.addEventListener('titleUpdate', function(e) {
		$("#mui-title").text(e.detail);
	})

	//	监听IM连接：失败
	window.addEventListener('monitorImF', function(e) {
		mui.toast('IM连接失败，请稍后重试');
	});

	//	监听IM连接：成功时
	window.addEventListener('monitorImT', function(e) {
		console.log('监听IM连接' + JSON.stringify(e.detail));
		var msgcontentobj = {
			type: e.detail.type,
			data: {
				type: e.detail.data.type,
				content: e.detail.data.content,
				sendee: chatId,
				sender: loginif.id,
				msgid: e.detail.data.id
			}
		}
		redomChat(msgcontentobj);
	});

	//	收到消息回执：显示发送失败
	window.addEventListener('msgError', function(e) {
		//console.log('显示发送失败' + JSON.stringify(e.detail));
		var msgerr = e.detail;
		if(msgerr.type == 'groupChat') {
			if(msgerr.data.code) {
				var errid = msgerr.data.id;
				if($('#chat-content span').length > 0) {
					$.each($('#chat-content span'), function(index, item) {
						if($(item).attr('data-id') == errid) {
							$(item).show(); //显示错误图标 红色叹号
						};
					})
				}

				var delChatPage = plus.webview.getWebviewById('/html/sub-message.html');
				if(delChatPage) {
					mui.fire(delChatPage, 'delChatRectentMsg', errid);
				}
			}
		}

	});

	//	检测当前用户是否属于当前群聊成员
	function checkAuthor(groupid) {
		jczw.group.getGroupDetail(groupid, function(result) {
			if(result.errCode == 0) {
				console.log('result.data.member:' + JSON.stringify(result));
				if(result.data.member.length > 0) {
					$.each(result.data.member, function(index, item) {
						if(item.userId == loginif.id) {
							$('#mui-bar-bottom').show();
							return;
						}
					});
				}
			}
		})
	}

	//	获取单聊历史记录
	function getSigleChatinfo(type) {
		if($("#Loading").length > 0) {
			setTimeout(function() {
				document.body.removeChild(document.getElementById('Loading'));
			}, 200)
		}
		ctdj.im.getSingleChatMsgs(chatId, offset, limit, function(r) {
			if(r.success) {
				//console.log('获取单聊历史:' + JSON.stringify(r));
				totals = r.result.totalCount; //总条数
				var plimit = (totals % 10); //取余预算
				if(totals - offset > 10) {
					offset += 10;
				} else {
					offset += plimit;
				}

				if(r.result.items.length > 0) {

					//var hisrows = r.result.items.reverse();//数据倒序排列
					var hisrows = r.result.items;
					if(maillistInfo) {
						$.each(maillistInfo.users, function(index, users) {
							if(chatId == users.id) {
								if(hisrows.length > 0) { //图片转换
									$.each(hisrows, function(index, item) {
										if(item.type == 'image') { // 判断接收消息类型为图片时，转化为绝对路径展示
											item.content = ctdj.tools.handelImageFullUrl(item.content);
										}
									});
								}
								var nums = r.result.items.length > 9 ? r.result.totalCount : r.result.items.length; // 判断是否还有下一页
								var chathistoryDom = template('chatmsghistorytpl', {
									data: hisrows,
									logininf: loginif,
									sender: users,
									totalnums: nums
								});

								if(type == 1) { // 获取历史记录时，每次滚动条定位到下一条开始的位置  借助一个隐藏的DOM获取高度后再清空DOM内容
									$("#tempdom").append(chathistoryDom);
									type = $("#tempdom").height() > 1000 ? $("#tempdom").height() - 700 : $("#tempdom").height() - 200;
									$("#tempdom").html('');
								}
								$("#chatContent").prepend(chathistoryDom);
								setToBottom(type);
								return;
							}
						});
					}

				}
			}
		});
	}

	//	获取历史群聊记录
	function getGroupChatinfo(type) {
		ctdj.im.getGroupChatMsgs(chatId, offset, limit, function(r) {
			if(r.success) {
				totals = r.result.totalCount; //总条数
				var plimit = (totals % 10); //取余预算
				if(totals - offset > 10) {
					offset += 10;
				} else {
					offset += plimit;
				}

				//var groupshisrows = r.rows.reverse();
				var groupshisrows = r.result.items;
				/*
				 * 获取本地通讯录信息，通过群聊历史记录sender Id 来获取sender信息;重新构造群聊历史记录对象
				 */

				//bug待处理，轮询消息人员信息出错
				//console.log('groupshisrows:' + JSON.stringify(groupshisrows));
				/*console.log('消息条数：' + groupshisrows.length);*/
				if(groupshisrows.length > 0) {
					if(maillistInfo) {
						$.each(maillistInfo.users, function(index, users) {
							if(groupshisrows.length > 0) { //图片转换
								$.each(groupshisrows, function(index, item) {

									if(item.sender == users.id) {
										item.senderinfo = users;
									}
								});
							}
						});
					}
				}

				//console.log('groupshisrows111:' + JSON.stringify(groupshisrows));
				var nums = r.result.items.length > 9 ? r.result.totalCount : r.result.items.length; // 判断是否还有下一页
				/*console.log(nums);
				console.log('转换后groupshisrows:' + JSON.stringify(groupshisrows));*/

				//	处理历史消息记录:轮询消息人员信息出错(通讯录未找到人员信息则移除相关操作)
				if(groupshisrows.length > 0) {
					$.each(groupshisrows, function(index, item) {
						if(!item.senderinfo) {
							item.senderinfo = '';
						}

						if(item.type == 'image') { // 判断接收消息类型为图片时，转化为绝对路径展示
							item.content = ctdj.tools.handelImageFullUrl(item.content);
							item.thumb = thumbImage(ctdj.tools.handelImageFullUrl(item.content));
						}
					});
				}


				var chathistoryDom = template('chatmsgGroupshistorytpl', {
					data: groupshisrows,
					logininf: loginif,
					totalnums: nums
				});

				if(type == 1) { // 获取历史记录时，每次滚动条定位到下一条开始的位置  借助一个隐藏的DOM获取高度后再清空DOM内容
					$("#tempdom").append(chathistoryDom);
					type = $("#tempdom").height() > 1000 ? $("#tempdom").height() - 700 : $("#tempdom").height() - 200;
					$("#tempdom").html('');
				}
				$("#chatContent").prepend(chathistoryDom);
				setToBottom(type);
				if($("#Loading").length > 0) {
					setTimeout(function() {
						document.body.removeChild(document.getElementById('Loading'));
					}, 200)
				}
				return;
			}
		});
	};

	//	检查对象是否为数组
	function isArray(o) {
		return Object.prototype.toString.call(o) == '[object Array]';
	}

	//渲染界面
	function renderDom(info, id) {
		console.log('info' + JSON.stringify(info));
		var arr = new Array();
		if(!isArray(info)) {
			arr.push(info);
		} else {
			arr = info;
		}

		$.each(arr, function(index, item) {
			if(item.data.type == 'image') { // 判断接收消息类型为图片时，转化为绝对路径展示
				item.data.content = ctdj.tools.handelImageFullUrl(item.data.content);
			}
		});

		if(id == '') {
			var chatDom = template('chatmsgtpl', {
				data: arr,
				logininf: loginif
			});

			$("#chatContent").append(chatDom);

			$('#chat-content').animate({
				scrollTop: $("#chatContent")[0].scrollHeight //置底操作
			}, 10);

		} else {
			//console.log('id:' + id);
			if(maillistInfo) {
				$.each(maillistInfo.users, function(index, users) {
					if(id == users.id) {
						var chatDom = template('chatmsgtpl', {
							data: arr,
							logininf: loginif,
							sender: users
						});
						$("#chatContent").append(chatDom);
						$('#chat-content').animate({
							scrollTop: $("#chatContent")[0].scrollHeight //置底操作
						}, 10);
					}
				})
			}

		}

		mui.previewImage();

	}

	//	消息置底功能
	function setToBottom(type) {
		if(type == 0) {
			$('#chat-content').animate({
				scrollTop: $("#chatContent")[0].scrollHeight //置底操作
			}, 10);
		} else { // 获取历史记录不用置底
			$("#chat-content").animate({
				scrollTop: type //置底操作
			}, 10);
		}

		mui.previewImage();
	}

	//初始化事件
	function initEvt() {

		//	发送图片
		mui('body').on('tap', '#msg-image', function() {
			if(!checkloginWork()) {
				mui.toast('当前登陆用户数据异常，不能发送消息');
				return;
			}
			var opts = [{
				title: '拍照'
			}, {
				title: '从相册选择'
			}];

			plus.nativeUI.actionSheet({
				//title: '发送图片',
				buttons: opts,
				cancel: '取消'
			}, function(opps) {
				switch(opps.index) {
					case 0:
						break;
					case 1:
						userCamera();
						break;
					case 2:
						gallery();
						break;
					default:
						break
				}
			});
		});

		//	发送消息(文本格式)
		mui('body').on('tap', '#btnsend', function() {

			if(!checkloginWork()) {
				mui.toast('当前登陆用户数据异常，不能发送消息');
				return;
			}

			//	监听网络
			ctdj.checkConnection(function(result) {
				if(result) {
					var content = $.trim($("#txt-msg").val());
					if(content == '') {
						return;
					}

					var msgcontentobj = {
						type: msgtype,
						data: {
							type: 'text',
							content: content,
							sendee: chatId,
							sender: loginif.id
						}
					}

					// 推送消息到指定单聊or群聊
					var h = plus.webview.getWebviewById('main.html');
					mui.fire(h, 'send', msgcontentobj);

				} else {
					mui.toast('网络异常,请稍后重试');
					// 检查网络
					var h = plus.webview.getWebviewById('main.html');
					mui.fire(h, 'checkNetworkinfo');
				}
			});
		});

		// 单聊个人详情or 群聊进入设置
		mui('body').on('tap', '#btninfo', function() {
			var status = this.getAttribute('data-status');
			console.log('userinfo:' + JSON.stringify(userinfo));
			if(status == 0) {
				//查看个人详情
				mui.openWindow({
					url: '/html/my-center.html',
					id: 'my-center',
					createNew: false,
					extras: {
						"info": userinfo,
						'userid': chatId
					},
					show: {
						autoShow: true,
						aniShow: 'slide-in-right',
						duration: 300
					},
					waiting: {
						autoShow: false,
						title: '正在加载...'
					}
				});
			} else { //查看群聊设置
				mui.openWindow({
					url: '/html/chat-groupsinfo.html',
					id: 'chat-groupsinfo',
					createNew: false,
					extras: {
						"userid": chatId
					},
					show: {
						autoShow: true,
						aniShow: 'slide-in-right',
						duration: 300
					},
					waiting: {
						autoShow: false,
						title: '正在加载...'
					}
				})
			}
		});

		document.querySelector('#chat-content').addEventListener('click', function(event) {
			if(!focus) {
				document.querySelector('#txt-msg').blur();
			}
		})

	}

	// 手机拍照
	var userCamera = function() {
		var camera = plus.camera.getCamera(); //获取手机摄像头对象
		var res = camera.supportedImageResolutions[0];
		var fmt = camera.supportedImageFormats[0];

		//调用拍照操作
		camera.captureImage(function(path) {
			plus.io.resolveLocalFileSystemURL(path, function(entry) {
				var filename;
				// 可通过entry对象操作上传的文件文件
				entry.file(function(file) {
					var fileReader = new plus.io.FileReader();
					//	文件名
					if(file.name.indexOf('.') > -1) {
						filename = file.name.split('.')[0];
					} else {
						filename = 'v' + new Date().getTime();
					}
				});

				var localpath = entry.toLocalURL() + "?version=" + new Date().getTime();
				var path = plus.io.convertLocalFileSystemURL(localpath); //转换为平台相对路径
				upload(localpath);
			}, function(error) {
				mui.toast('没有选择图片');
			});
		}, function(error) {
			mui.toast('拍照失败');
		}, {
			resolution: res,
			format: fmt
		})
	}

	// 从相册中筛选
	var gallery = function() {
		plus.gallery.pick(function(path) {
			var filename = 'v=' + new Date().getTime();
			var localpath = plus.io.convertLocalFileSystemURL(path);
			upload(localpath);
		}, function(err) {
			mui.toast('取消选择');
			console.log('gallery errcode=' + err.code);
			console.log('gallery errmsg=' + err.message);
		}, { //文件过滤，只能筛选图片文件
			filter: 'image',
			multiple: false
		})
	}

	// 上传图片
	var upload = function(path) {
		ctdj.checkToken(function(token) {
			var waiting = plus.nativeUI.showWaiting('上传中...', {
				back: 'close'
			});
			plus.zip.compressImage({
				src: path,
				dst: '_downloads/zip.jpg',
				overwrite: true,
				/*
								width: '800px',
								height: '900px',*/
				quality: 50
			}, function(e) {
				var uploadObj = plus.uploader.createUpload(config.uploadFile, {
					method: 'post',
					priority: 100
				}, function(r, status) {
					if(status == 200) {
						var rJson = JSON.parse(r.responseText);
						if(rJson.success) {
							//console.log("rJson.result.filePath:" + rJson.result[0].filePath);
							//var filePath = ctdj.tools.handelImageFullUrl(rJson.result[0].filePath);//更改图片路径为绝对路径
							var filePath = rJson.result[0].filePath;
							var msgcontentobj = {
								type: msgtype,
								data: {
									type: 'image',
									content: filePath,
									sendee: chatId,
									sender: loginif.id
								}
							}

							// 推送消息到指定单聊or群聊
							var h = plus.webview.getWebviewById('main.html');
							mui.fire(h, 'send', msgcontentobj);
						}

						/*if(rJson.errCode == 0) { // 上传成功，发送
							send(2, rJson.data[0].accessUrl);
						}*/
					} else {
						console.log("Upload failed: " + status);
					}
					waiting.close();
				});
				uploadObj.addFile(e.target, {
					key: 'filename',
				});
				uploadObj.addData("type", "chat"); // 

				uploadObj.setRequestHeader('Authorization', "Bearer " + token.access_token); //添加token
				//uploadObj.addEventListener( "statechanged", onStateChanged, false );
				uploadObj.start();
			}, function(err) {

			});
		});

	}

	//	DOM渲染
	function redomChat(msgcontentobj) {
		console.log('js=' + JSON.stringify(msgcontentobj));
		renderDom(msgcontentobj, ''); //渲染界面
		$("#txt-msg").val(''); //清空输入框信息

		//	推送到本人最近会话信息
		var msgchatPage = plus.webview.getWebviewById('/html/sub-message.html');
		if(msgchatPage) {
			msgcontentobj.read = 1;
			msgcontentobj.name = loginif.name;
			mui.fire(msgchatPage, 'newChatRectentMsg', msgcontentobj);
		}
	}

	//	图片路径转换,新增预览图
	function thumbImage(imgPath) {

		var extStrat = imgPath.lastIndexOf('.');
		var ext = imgPath.substring(extStrat, imgPath.length).toUpperCase();
		var thumbpath = imgPath.substring(0, extStrat) + '.thumb' + imgPath.substring(extStrat, imgPath.length);
		return thumbpath;

		/*if(ext == ".BMP" || ext == ".PNG" ||  ext == ".GIF" && ext == ".JPG" ||  ext == ".JPEG") {
			imgPath = imgPath.substring(0, extStrat) + '.thumb' + imgPath.substring(extStrat, imgPath.length);
			console.log('imgPath:' + imgPath);
			
		}
		return imgPath;
		console.log(imgPath);*/
	}

	// 查看历史记录
	mui('body').on('tap', '#chatContent .showmore', function() {
		$(this).remove();
		if(totals != 0) {
			var h = 1; //滚动条距顶端的距离  
			if(msgtype == 'singleChat') { //单聊
				if(totals >= offset) {
					getSigleChatinfo(h);
				} else {
					$(this).remove();
					mui.toast('暂无更多数据')
				}
			} else { //群聊
				if(totals >= offset) {
					getGroupChatinfo(h);
				} else {
					$(this).remove();
					mui.toast('暂无更多数据')
				}
			}
		} else {
			mui.toast('暂无历史数据');
		}

	});

	//	检查当前的登录用户有效性
	function checkloginWork() {
		var checkflag = true;
		if(loginif.userName == 'UnknownUser' && loginif.name == '未知用户') {
			checkflag = false;
		}

		return checkflag;
	}
</script>